package com.woniuxy.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Date;

/*JWT工具类*/
public class JWTUtils {
    private static final String SECRET_KEY="woniuxy";
    private static final long EXPIRES = 10 * 1000 * 60;//10分钟过期时间
    /*生成token*/
    public static String sign(String username,String password){
        long extime = System.currentTimeMillis() + EXPIRES;
        return JWT.create().withClaim("username",username)
                .withExpiresAt(new Date(extime))
                .sign(Algorithm.HMAC256(username+password+SECRET_KEY));
    }
    /*通过token返回用户名信息*/
    public static String getUsername(String token){
        DecodedJWT decode = JWT.decode(token);
        return decode.getClaim("username").asString();
    }
    /*返回校验结果*/
    public static boolean verify(String token,String username,String password){
        //通过JWT工具类底层，帮你生成新的token，来判断之前的token有没有被篡改
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(username+password+SECRET_KEY)).withClaim("username",username).build();
        jwtVerifier.verify(token);
        return true;
    }
}
